const exp = require('express');
const { resolve } = require('path');
const userRouter = exp.Router();
const formidable = require('formidable');
const userModel = require('../db/models/userModel');
const md5 = require('md5');
const { RES_CODE } = require('../utils/constants');
userRouter.use(exp.urlencoded({ extended: false }));
let readFile = formidable({
    uploadDir: resolve(__dirname, "../public/upload"),
    keepExtensions: true
})
//获取用户分页列表
// page = 3
// limit = 6
userRouter.get('/user/:page/:limit', async (req, res) => {

    // 1. 获取前端 发送来的参数》page、limit
    let { page, limit } = req.params;

    let page1 = (page - 1) * limit;

    // 从数据库中截取我需要的部分
    let users = await userModel.find().skip(page1).limit(limit);

    let total = await userModel.count();

    res.json({
        code: RES_CODE.SUCCESS,
        msg: "获取列表成功",
        data: {
            users,
            total
        }
    });
});

// 添加用户
userRouter.post('/user', (req, res) => {
    // 获取到表单数据 - 有附件的表单 - 多媒体表单 数据提交 不能body获取
    // 用户名、密码、头像
    // 解析有附件表单的方法
    readFile.parse(req, async (err, fields, files) => {
        if (err) {
            console.log("解析表单有误");
            return;
        }
        // console.log(fields);
        // console.log(files);

        // 将上传的图片路径得到
        let imgUrl = '/upload/' + files.profile.newFilename;
        try {
            // 判断用户名是否已经存在
            let user = await userModel.findOne({ username: fields.username })
            console.log(user);
            if (!user) {
                // // 插入数据库
                let newUser = await userModel.create({
                    username: fields.username,
                    pwd: md5(fields.pwd),
                    profile: imgUrl
                })
                res.json({
                    code: RES_CODE.SUCCESS,
                    msg: "添加用户成功",
                    data: newUser
                })
            } else {
                res.json({
                    code: RES_CODE.DATA_ERROR,
                    msg: "抱歉，此用户名已被占用"
                })
            }
        } catch (error) {
            res.json({
                code: RES_CODE.SERVER_ERROR,
                msg: "抱歉，服务器出错，请稍后再试"
            })
        }
    })
})

// 获取用户信息
userRouter.get('/user', async (req, res) => {
    // 获取用户的id
    let { id } = req.query;
    try {
        // 通过id去数据库中找匹配的数据
        let user = await userModel.findById(id);
        res.json({
            code: RES_CODE.SUCCESS,
            msg: "获取用户信息成功",
            data: user
        })
    } catch (error) {
        res.json({
            code: RES_CODE.DATA_ERROR,
            msg: "id无效，获取用户信息失败",
        })
    }
})

//删除用户
userRouter.delete('/user/:id',async(req,res)=>{

    // 获取id
    let {id} = req.params;
    
    // 通过id删除一条数据
    await userModel.deleteOne({_id:id})

    res.json({
        code:RES_CODE.SUCCESS,
        msg:"删除成功"
    })
})

// 修改用户
userRouter.put('/user',(req,res)=>{
    // let {_id} = req.params;
    readFile.parse(req,async (err,fields,files)=>{
        if(err){
            res.json({
                code:RES_CODE.DATA_ERROR,
                msg:"抱歉，表单数据解析失败"
            })
        }else{
            let imgUrl = '/upload/'+files.profile.newFilename;
            try {

                await userModel.updateOne({_id:fields._id},{
                    username:fields.username,
                    profile:imgUrl
                })

                res.json({
                    code:RES_CODE.SUCCESS,
                    msg:"更新用户成功"
                })
            } catch (error) {
                res.json({
                    code:RES_CODE.SERVER_ERROR,
                    msg:"更新用户失败"
                })
            }
        }
    })
})

module.exports = userRouter;